package com.cn.shuangzi.userinfo.activity;

import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.cn.shuangzi.SZBaseActivity;
import com.cn.shuangzi.activity.SZInterfaceActivity;
import com.cn.shuangzi.common.SZCommonEvent;
import com.cn.shuangzi.loginplugin.common.socialized.ShareWeChat;
import com.cn.shuangzi.loginplugin.common.socialized.ThirdLogin;
import com.cn.shuangzi.retrofit.SZCommonResponseListener;
import com.cn.shuangzi.retrofit.SZRetrofitManager;
import com.cn.shuangzi.userinfo.R;
import com.cn.shuangzi.userinfo.bean.AccountAllBindInfo;
import com.cn.shuangzi.userinfo.bean.AccountBindInfo;
import com.cn.shuangzi.userinfo.common.UserManager;
import com.cn.shuangzi.util.SZToast;
import com.cn.shuangzi.util.SZUtil;
import com.cn.shuangzi.view.sweet_alert.SweetAlertDialog;
import com.google.gson.Gson;

import org.greenrobot.eventbus.Subscribe;

public abstract class SZAccountSafeActivity extends SZBaseActivity implements ThirdLogin.OnThirdLoginResponseListener, SZInterfaceActivity {
    public RelativeLayout rltBindPhone;
    public TextView txtPhone;
    public LinearLayout lltThirdPlatform;
    public LinearLayout lltWeChatBind;
    public LinearLayout lltWeChat2Bind;
    public LinearLayout lltWeChatChange2Bind;
    public ImageView imgWeChatBind;
    public ImageView imgWeChat2Bind;
    public ImageView imgWeChatChange2Bind;
    public TextView txtWeChat;
    public TextView txtWeChatChange2;
    public TextView txtWeChat2;

    public LinearLayout lltContactService;

    public LinearLayout lltCancellationAccount;
    public TextView txtCancellationAccount;
    public AccountAllBindInfo accountAllBindInfo;

    public static ThirdLogin thirdLogin;

    @Override
    protected int onGetChildView() {
        return R.layout.activity_account_safe;
    }

    @Override
    protected void onBindChildViews() {

        rltBindPhone = findViewById(R.id.rltBindPhone);
        txtPhone = findViewById(R.id.txtPhone);
        lltThirdPlatform = findViewById(R.id.lltThirdPlatform);
        lltWeChatBind = findViewById(R.id.lltWeChatBind);
        lltWeChat2Bind = findViewById(R.id.lltWeChat2Bind);
        lltWeChatChange2Bind = findViewById(R.id.lltWeChatChange2Bind);
        imgWeChatBind = findViewById(R.id.imgWeChatBind);
        imgWeChat2Bind = findViewById(R.id.imgWeChat2Bind);
        imgWeChatChange2Bind = findViewById(R.id.imgWeChatChange2Bind);
        txtWeChat = findViewById(R.id.txtWeChat);
        txtWeChat2 = findViewById(R.id.txtWeChat2);
        txtWeChatChange2 = findViewById(R.id.txtWeChatChange2);

        lltCancellationAccount = findViewById(R.id.lltCancellationAccount);
        txtCancellationAccount = findViewById(R.id.txtCancellationAccount);

        lltContactService = findViewById(R.id.lltContactService);
    }

    @Override
    protected void onBindChildListeners() {
        lltContactService.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ShareWeChat.getInstance().openCompanyService(
                        "ww319db112ce746335","https://work.weixin.qq.com/kfid/kfc539223cd934af350"
                );
            }
        });
        txtCancellationAccount.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(getCancellationAccountConditionActivity());
            }
        });
        rltBindPhone.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (accountAllBindInfo.isBindPhone()) {
                    startActivity(accountAllBindInfo.getPHONE().getBoundName(),getCheckOldPhoneActivity());
                }else{
                    startActivity(getBindPhoneActivity());
                }
            }
        });
        imgWeChatBind.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(accountAllBindInfo.isBindWeChat()){
                    showWarningAlert("解除微信绑定", "确定要解除绑定吗？", new SweetAlertDialog.OnSweetClickListener() {
                        @Override
                        public void onClick(SweetAlertDialog sweetAlertDialog) {
                            sweetAlertDialog.dismissWithAnimation();
                            showBarTransparentStyle();
                            request(SZRetrofitManager.getInstance().getSZRequest().unbindThirdPlatformV2(getUserId(), UserManager.PLATFORM_WECHAT), new SZCommonResponseListener() {
                                @Override
                                public void onResponseSuccess(String data) {
                                    SZToast.success("已解除微信绑定！");
                                    accountAllBindInfo.setWECHAT(null);
//                                    setCheck(imgWeChatBind, accountAllBindInfo.isBindWeChat());
                                    initBindView();
                                    closeBar();
                                }

                                @Override
                                public void onResponseError(int errorCode, String errorMsg) {
                                    closeBar();
                                }
                            });
                        }
                    });
                }else{
                    showWarningAlert("绑定微信", "确定去绑定微信吗？", new SweetAlertDialog.OnSweetClickListener() {
                        @Override
                        public void onClick(SweetAlertDialog sweetAlertDialog) {
                            sweetAlertDialog.dismissWithAnimation();
                            loginWeChat();
                        }
                    });
                }
            }
        });
        imgWeChat2Bind.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(accountAllBindInfo.isBindWeChat2()){
                    showWarningAlert("解除微信绑定", "确定要解除绑定吗？", new SweetAlertDialog.OnSweetClickListener() {
                        @Override
                        public void onClick(SweetAlertDialog sweetAlertDialog) {
                            sweetAlertDialog.dismissWithAnimation();
                            showBarTransparentStyle();
                            request(SZRetrofitManager.getInstance().getSZRequest().unbindThirdPlatformV2(getUserId(), UserManager.PLATFORM_WECHAT_2), new SZCommonResponseListener() {
                                @Override
                                public void onResponseSuccess(String data) {
                                    SZToast.success("已解除微信绑定！");
                                    accountAllBindInfo.setWECHAT_2(null);
                                    initBindView();
                                    closeBar();
                                }

                                @Override
                                public void onResponseError(int errorCode, String errorMsg) {
                                    closeBar();
                                }
                            });
                        }
                    });
                }else{
                    showWarningAlert("绑定微信", "确定去绑定微信吗？", new SweetAlertDialog.OnSweetClickListener() {
                        @Override
                        public void onClick(SweetAlertDialog sweetAlertDialog) {
                            sweetAlertDialog.dismissWithAnimation();
                            loginWeChat();
                        }
                    });
                }
            }
        });
        imgWeChatChange2Bind.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(!accountAllBindInfo.isBindWeChat2()){
                    showWarningAlert("绑定微信", "重新绑定后，将持续保障您的账号安全！","去绑定","取消", new SweetAlertDialog.OnSweetClickListener() {
                        @Override
                        public void onClick(SweetAlertDialog sweetAlertDialog) {
                            sweetAlertDialog.dismissWithAnimation();
                            loginWeChat();
                        }
                    });
                }else{
                    SZToast.success("您的账号，已重新绑定了微信！");
                    initBindView();
                }
            }
        });
    }

    public void setCheck(ImageView imgView, boolean isCheck) {
        imgView.setImageResource(isCheck ? R.mipmap.ic_switch_on : R.mipmap.ic_switch_off);
    }

    @Override
    protected void onChildViewCreated() {
        onChildViewCreatedPre();
        showBackImgLeft(getBackImgLeft());
        setTitleTxt(R.string.txt_account_safe);
        if(isWeChatChangeMode()&&isWeChat2Mode()){
            throw new IllegalStateException("isWeChatChangeMode 和 isWeChat2Mode 返回值不能同时为true");
        }

        if (iShowBindView()) {
            isShowContent(false);
            onReloadData(false);
        } else {
            rltBindPhone.setVisibility(View.GONE);
            lltThirdPlatform.setVisibility(View.GONE);
        }
        registEventBus();
    }

    @Override
    protected void onReloadData(boolean isRefresh) {
        showBarTransparentStyle();
        request(SZRetrofitManager.getInstance().getSZRequest().queryBindingInfo(getUserId()), new SZCommonResponseListener() {
            @Override
            public void onResponseSuccess(String data) {
                accountAllBindInfo = new Gson().fromJson(data, AccountAllBindInfo.class);
                isShowContent(true);
                initBindView();
            }

            @Override
            public void onResponseError(int errorCode, String errorMsg) {
                showErrorWithMsg(errorCode,errorMsg);
            }
        });
    }

    public void initBindView() {
        if (accountAllBindInfo.isBindPhone()) {
            onBindPhoneLoaded(accountAllBindInfo.getPHONE().getBoundName());
            txtPhone.setText(SZUtil.getHidePhoneStr(accountAllBindInfo.getPHONE().getBoundName()));
        } else {
            txtPhone.setText("去绑定");
        }
        if(isWeChatChangeMode()){
            /**
             * 直接显示wechat2的条件
             * 1.已绑定了微信2
             * 2.已绑定手机号，并且微信和微信2都未绑定的用户
             */
            if(accountAllBindInfo.isBindWeChat2()||(accountAllBindInfo.isBindPhone()&&!accountAllBindInfo.isBindWeChat()&&!accountAllBindInfo.isBindWeChat2())){
                lltWeChatBind.setVisibility(View.GONE);
                lltWeChat2Bind.setVisibility(View.VISIBLE);
                lltWeChatChange2Bind.setVisibility(View.GONE);
                setCheck(imgWeChat2Bind, accountAllBindInfo.isBindWeChat2());
                txtWeChat2.setText("微信"+(accountAllBindInfo.isBindWeChat()?"（已绑定）":"（未绑定）"));
            }else{
                lltContactService.setVisibility(View.VISIBLE);
                lltWeChatBind.setVisibility(View.GONE);
                lltWeChat2Bind.setVisibility(View.GONE);
                lltWeChatChange2Bind.setVisibility(View.VISIBLE);
                setCheck(imgWeChatChange2Bind, accountAllBindInfo.isBindWeChat2());
            }
        } else if(isWeChat2Mode()){
            lltWeChatBind.setVisibility(View.GONE);
            lltWeChatChange2Bind.setVisibility(View.GONE);
            lltWeChat2Bind.setVisibility(View.VISIBLE);
            setCheck(imgWeChat2Bind, accountAllBindInfo.isBindWeChat2());
            txtWeChat2.setText("微信"+(accountAllBindInfo.isBindWeChat()?"（已绑定）":"（未绑定）"));
        } else {
            lltWeChatBind.setVisibility(View.VISIBLE);
            lltWeChat2Bind.setVisibility(View.GONE);
            lltWeChatChange2Bind.setVisibility(View.GONE);
            setCheck(imgWeChatBind, accountAllBindInfo.isBindWeChat());
            txtWeChat.setText("微信"+(accountAllBindInfo.isBindWeChat()?"（已绑定）":"（未绑定）"));
        }
        onGetAccountAllBindInfo(accountAllBindInfo);
    }
    @Subscribe
    public void onSZCommonEvent(SZCommonEvent szCommonEvent){
        switch (szCommonEvent.getEvent()){
            case SZCommonEvent.BIND_PHONE_EVENT:
                accountAllBindInfo.setPHONE(new AccountBindInfo(szCommonEvent.getObject().toString(),true));
                txtPhone.setText(SZUtil.getHidePhoneStr(accountAllBindInfo.getPHONE().getBoundName()));
                break;
        }
    }
    public void loginWeChat() {
        if (SZUtil.isAppInstalled("com.tencent.mm")) {
            showBarTransparentStyle();
            thirdLogin = new ThirdLogin(this, ThirdLogin.WE_CHAT_PLATFORM, this);
            thirdLogin.login();
        } else {
            SZToast.warning("您还没有安装微信!");
        }
    }
    private boolean isRequestingUserInfo;
    @Override
    public void onSuccess(String thirdId) {
        bindWeChat(thirdId);
    }
    public void bindWeChat(String code){
        if(!isRequestingUserInfo) {
            isRequestingUserInfo = true;
            showBarTransparentStyle();
            final boolean isWeChat2 = isWeChat2Mode() || isWeChatChangeMode();

            String platform;
            if(isWeChat2){
                platform = UserManager.PLATFORM_WECHAT_2;
            }else{
                platform = UserManager.PLATFORM_WECHAT;
            }
            request(SZRetrofitManager.getInstance().getSZRequest().bindThirdPlatformV2(getUserId(), code, platform), new SZCommonResponseListener() {
                @Override
                public void onResponseSuccess(String data) {
                    isRequestingUserInfo = false;
                    closeBar();
                    if(isWeChat2){
                        accountAllBindInfo.setWECHAT_2(new AccountBindInfo(true));
                    }else {
                        accountAllBindInfo.setWECHAT(new AccountBindInfo(true));
                    }
                    initBindView();
                    showSuccessAlert("绑定成功","恭喜您，微信已绑定成功，可用微信号进行登录啦~");
                }

                @Override
                public void onResponseError(int errorCode, String errorMsg) {
                    isRequestingUserInfo = false;
                    closeBar();
                }
            });
        }
    }
    @Override
    public void onFailed() {
        closeBar();
    }

    @Override
    public void onCancel() {
        closeBar();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        thirdLogin = null;
    }
    public abstract Class getCancellationAccountConditionActivity();

    public abstract Class getBindPhoneActivity();

    public abstract Class getCheckOldPhoneActivity();

    public abstract boolean iShowBindView();

    public abstract String getUserId();

    public abstract void onBindPhoneLoaded(String phone);

    public abstract void onGetAccountAllBindInfo(AccountAllBindInfo accountAllBindInfo);

    public boolean isWeChatChangeMode(){
        return false;
    }

    public boolean isWeChat2Mode(){
        return false;
    }

}
